package com.me.chat.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * @Author VULCAN
 * @create 2020/2/7 16:50
 * @Des 资源服务器         ps：资源服务器与授权服务器在同一个服务器里面，担任两个的角色
 */
@EnableResourceServer//我是资源服务器
@Configuration
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    private static final String RESOURCE_ID="res1";//资源客户端id

    @Autowired
    RedisConnectionFactory factory;

    @Bean//令牌存储策略  在哪里保存就在哪里取得
    public TokenStore tokenStore(){
        return new RedisTokenStore(factory);
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(RESOURCE_ID)//指定自己的资源id
                .tokenStore(tokenStore())//从哪里取得就从哪里获取（解析）
                .stateless(true);
    }

    @Override // 细节配置
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/res/**").access("#oauth2.hasScope('all')")
                .and()
                .csrf()
                .disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);//因为用了token令牌的方式，就不需要session了，关闭session
    }

}
